<template>
    <div class="hone-goods-list"> 
        <van-pull-refresh v-model="loading" @refresh="onRefresh">

        <van-list class="list-box"
            :finished="is_finish"
            finished-text="没有更多了"
            @load="loadHandler">
        <van-cell class="item-box" v-for="item in goodList" :key="item.proid" >
                <img :src="item.img1"  class="img">
                <p class="text">{{ item.proname }}</p>
                <p class="price">￥{{ item.originprice.toFixed(2)}}</p>
        </van-cell>
    </van-list>
</van-pull-refresh>
    </div>
</template>

<script lang="ts" setup>
import {homeGoodList} from'@/apis/goodsList'
import { watch } from 'vue';
import { ref ,onMounted} from 'vue'; 



interface goods {
    proid: string
    img1:string
    proname: string
    originprice: number

}

let goodList = ref<goods[]>([])
const count = ref<number>(0)
const flag = ref<boolean>(true)

//准备变量，表示数据是否完结
const is_finish=ref<boolean>(false)
//是否处于加载中的状态
const loading = ref<boolean>(false)

const getList =async()=>{
    const res = await homeGoodList(count.value,10)

    if(res.data.length<10) {
        is_finish.value=true
        return 
    }
    
    goodList.value.push(...res.data)
    flag.value=true
    loading.value=false

}
const loadHandler=()=> {
    if(!flag.value) return
    flag.value=false
    count.value++
    getList()
}


//下拉刷新的函数
const onRefresh =()=>{
    const num = Math.floor(Math.random() * 5) + 1
  // 判断: 如果随机出来的数字和 count 一致, 再来一遍
  if (num === count.value) {
    onRefresh()
    return
  }

  // 注意: 咱们为了模拟效果, 每次让 count 改变为 1 ~ 5 的随机数
  count.value = num

  // 注意: 应该把原始数组清空
  goodList.value = []

  is_finish.value=false
}

watch(count, () => getList())


onMounted(()=>{
    getList()
})

</script>

<style scoped lang="scss">
.hone-goods-list{
    width: 100%;
    box-sizing: border-box;
    padding: 20px 10px 0 10px;
    height: 100px;
}

.img{
    width: 100%;
}
.text {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    text-align: left;
    // padding: 5px 6px;
}
.price{
    color: red;
    font-weight: 700;
    text-align: left;
}
.list-box{
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.item-box{
    width: 48%;
    border-radius: 10px;
    background-color: #fff;
     overflow: hidden;
     margin-bottom: 10px;
}
</style>